import requests
import json
from PyQt5.QtCore import QThread, pyqtSignal
from app.common.setting import USER_LOGIN, ENCRYPTION_STATION, CONFIG_FOLDER
from app.ui_controller.ui_pool import Ui_Pool, Portal_Pool


class LoginThread(QThread):
    def __init__(self, account, password, service):
        super().__init__()
        self.account = account
        self.password = password
        self.service = service

    def run(self):
        try:
            r = requests.post(USER_LOGIN, json={"account": self.account, "password": self.password})
            result = json.loads(r.text)
            msg = result["msg"]
            print(result)
            if msg == "成功":
                storageInformation = ENCRYPTION_STATION.encrypt(str(result).encode())
                with open(f"{CONFIG_FOLDER}/userInformation.bin", "wb") as f:
                    f.write(storageInformation)
                Portal_Pool.portals["user"] = result
                    
                self.service.result = True  # 直接设置服务实例的属性
            else:
                self.service.result = False
        except requests.RequestException as e:
            print(f"请求失败: {e}")
            self.service.result = False

class AccountService:
    """License service"""

    def __init__(self):
        self.result = None

    def validate(self, password: str, account: str):
        """Verify if the activation code is legal"""
        self.accountLogin = LoginThread(password=password, account=account, service=self)
        self.accountLogin.start()
        self.accountLogin.wait()  # 等待线程结束

        return self.result
    
